package com.campusbook.service.impl;

import com.campusbook.dao.BookDao;
import com.campusbook.dao.BorrowRecordDao;
import com.campusbook.model.Book;
import com.campusbook.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;
    
    @Autowired
    private BorrowRecordDao borrowRecordDao;

    private static final String UPLOAD_DIR = "src/main/webapp/uploads/";

    @Override
    @Cacheable(value = "books", key = "#id")
    public Book findById(Long id) {
        return bookDao.findById(id);
    }

    @Override
    @Cacheable(value = "availableBooks")
    public List<Book> findAvailableBooks() {
        return bookDao.findAvailableBooks();
    }

    @Override
    public List<Book> findByOwnerId(Long ownerId) {
        return bookDao.findByOwnerId(ownerId);
    }

    @Override
    @CacheEvict(value = {"books", "availableBooks"}, allEntries = true)
    public void save(Book book) {
        bookDao.save(book);
    }

    @Override
    @CacheEvict(value = {"books", "availableBooks"}, allEntries = true)
    public void update(Book book) {
        bookDao.update(book);
    }

    @Override
    @CacheEvict(value = {"books", "availableBooks"}, allEntries = true)
    public void delete(Long id) {
        bookDao.delete(id);
    }

    @Override
    public boolean borrowBook(Long bookId, Long borrowerId) {
        Book book = bookDao.findById(bookId);
        if (book == null || !"AVAILABLE".equals(book.getStatus())) {
            return false;
        }
        
        // 更新图书状态
        bookDao.updateStatus(bookId, "BORROWED");
        
        // 创建借阅记录
        borrowRecordDao.save(bookId, borrowerId, book.getOwnerId(), 
                LocalDateTime.now().plusDays(30));
        
        return true;
    }

    @Override
    public boolean returnBook(Long bookId, Long borrowerId) {
        // 实现还书逻辑
        return true;
    }

    @Override
    public String saveCoverImage(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return null;
        }
        
        // 创建上传目录
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path filePath = uploadPath.resolve(filename);
        Files.copy(file.getInputStream(), filePath);
        
        return "/uploads/" + filename;
    }
}
